package com.itwp.jd.service;

import com.itwp.jd.pojo.Content;
import com.itwp.jd.utils.HtmlParseUtil;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Carl Wu on 2020/4/28 2:04
 */
@Service
public class ContentService {

    @Autowired
    private SolrClient solrClient;

    public Boolean parseContent(String Keywords) throws Exception {
        List<Content> contents = new HtmlParseUtil().parseJD(Keywords);
        int i = 1;
        for (Content content : contents) {
            content.setId(UUID.randomUUID().toString());
            solrClient.addBean(content);
        }
        solrClient.commit();
        return true;
    }

    public List<Content> searchPageHighlightBuilder(String keyword, int pageNo, int pageSize) throws IOException, SolrServerException {

        if (pageNo <= 1){
            pageNo = 1;
        }
        keyword= URLDecoder.decode(keyword, "UTF-8");

        SolrQuery solrQuery = new SolrQuery();

        //分页
        solrQuery.setStart(pageNo);
        solrQuery.setRows(pageSize);

        solrQuery.set("q","c_title:"+keyword);

        /**
         * h1设置高亮
         */
        solrQuery.setHighlight(true);
        solrQuery.addHighlightField("c_title");
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");

        QueryResponse response = solrClient.query(solrQuery);

        /**
         * 高亮数据打印
         */
        Map<String, Map<String, List<String>>> map = response.getHighlighting();


        List<Content> contents = response.getBeans(Content.class);
        contents.forEach(content -> {
            Map<String, List<String>> map1 = map.get(content.getId());
            List<String> list = map1.get("c_title");
            if (list != null){  //防止*:*
                String c_title = list.get(0);
                content.setTitle(c_title);
            }
        });

        return contents;
    }
}
